package auth

import (
	"log"
	"youdu/config"
	modelYoudu "youdu/model/youdu"
	"youdu/service/yodoo/sso"

	"github.com/gin-gonic/gin"
)

func YouduSSOAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		var Identify modelYoudu.Identify
		var err error
		// 开发版本
		if config.Inst.App.Debug == 1 {
			sso.SetIdentifyFromDemo(c)
			c.Next()
			return
		}
		// 获取token
		token := c.Query("token")
		if token == "" {
			if c.Request.URL.Path == "/jielong/" {
				resError(c, "非法请求路径或者参数")
				return
			}
			// 没有token就尝试从session获取
			Identify, err = sso.GetIdentifyFromSession(c)
			if err != nil {
				resError(c, "SESSION 验证错误", err)
				return
			}
			sso.SetIdentifyToContext(c, Identify)
		} else {
			// 有token就从服务器获取
			Identify, err = sso.LoginByToken(token)
			if err != nil {
				resError(c, "SSO 登录错误", err)
				return
			}
			sso.SetIdentifyToSession(c, Identify)
		}
		if err != nil {
			resError(c, "SSO 登录错误", err)
			return
		}
		// 如果账号为空，则拦截
		if Identify.UserInfo.Account == "" {
			resError(c, "未知用户身份")
			return
		}
		log.Println("SetIdentifyFromDemo: ", config.Inst.App.Debug, Identify.UserInfo.Account, token, c.Request.URL.Path)
		c.Next()
	}
}

func resError(c *gin.Context, tip string, info ...interface{}) {
	log.Println(tip, info)
	// common.ResError(c, "请使用有度客户端打开")
	c.HTML(200, "jielong_400.html", gin.H{"title": tip})
	c.Abort()
}
